package com.jprocms.module.cms.controller.portal.page;

import com.jprocms.module.cms.controller.portal.api.InvestigateApiController;
import com.jprocms.module.cms.dal.dataobject.investigate.InvestigateDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.service.content.ContentCountService;
import com.jprocms.module.cms.service.investigate.InvestigateService;
import com.jprocms.module.cms.service.site.SiteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 前台调查页面
 *
 * @author jprocms
 */
@Controller
public class InvestigatePageController {

    private static final String TPL_INDEX = "sys/investigate";
    private static final String TPL_DETAIL = "sys/investigate_detail";
    private static final String TPL_RESULT = "sys/investigate_result";

    @GetMapping({"/investigate", "/{sitePath:[\\w-]+}/investigate"})
    public String list(@PathVariable(required = false) String sitePath, HttpServletRequest request) {
        SiteDO site = siteResolver.getSite(sitePath);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_INDEX);
    }

    @GetMapping({"/investigate/{id}", "/{sitePath:[\\w-]+}/investigate/{id}"})
    public String getDetail(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                            HttpServletRequest request, Map<String, Object> modelMap) {
        SiteDO site = siteResolver.getSite(sitePath);
        handleInvestigate(id, modelMap);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_DETAIL);
    }

    @GetMapping({"/investigate/{id}/result", "/{sitePath:[\\w-]+}/investigate/{id}/result"})
    public String result(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                         Map<String, Object> modelMap) {
        SiteDO site = siteResolver.getSite(sitePath);
        handleInvestigate(id, modelMap);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(TPL_RESULT);
    }

    private final SiteService siteResolver;
    private final InvestigateService service;
    private final ContentCountService contentCountService;

    public InvestigatePageController(SiteService siteService, InvestigateService service, ContentCountService contentCountService) {
        this.siteResolver = siteService;
        this.service = service;
        this.contentCountService = contentCountService;
    }

    private void handleInvestigate(Long id, Map<String, Object> modelMap) {
        InvestigateDO investigate = service.getInvestigate(id);
        InvestigateApiController.validateInvestigate(id, investigate);
        modelMap.put("investigate", investigate);
    }
}
